package dbinit;

import java.sql.Date;
import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.price.model.Price;
import core.price.model.PriceType;
import core.util.HibernateCoreUtil;

public class InitPrice {
	public static Price getPriceByUuid(Long uuid)
	{
		Price p = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				p = (Price) session.get(Price.class, uuid);
				transaction.commit();
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return p ;
	}
	public static Price getPriceByProductIdAndPriceType(Long productId , Long ptId)
	{
		Price p = null ;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try 
		{
				transaction = session.beginTransaction();
				PriceType priceType = InitPriceType.getPriceTypeByUuid(ptId);
				Query q = session.createQuery("from Price p where p.productId = "+productId+" and p.priceType=:priceType").setEntity("priceType", priceType);
				Iterator<Price>pricelstItr = q.list().iterator();

				while(pricelstItr.hasNext())
				{
					p = pricelstItr.next();
			    }
		}
		catch (HibernateException e) 
		{
			// TODO: handle exception
			transaction.rollback();
			e.printStackTrace();
		}
		finally 
		{
			session.close();
		}
		return p ;
	}
	public static Long doinit(float price,float specialprice,Date startdate,Date enddate,Long ptId,String comment,Long productid)
	{
		Transaction transaction = null;
		Session session = HibernateCoreUtil.getSessionFactory().openSession();
		Price prc = null ;
		prc = getPriceByProductIdAndPriceType(productid,ptId);
		Long uuid = null;
		if(prc == null)
		{
			prc = new Price();
			prc.setPrice(price);
			prc.setSpecialprice(specialprice);
			prc.setStartdate(startdate);
			prc.setEnddate(enddate);
			prc.setComment(comment);
			prc.setProductId(productid);
			prc.setPriceType(InitPriceType.getPriceTypeByUuid(ptId));
			try
			{
				transaction = session.beginTransaction();
				uuid = (Long)session.save(prc);
				transaction.commit();
			}
			catch(HibernateException he)
			{
				he.printStackTrace();
			}
		}
		else
		{
			uuid = prc.getUuid();
		}
		return uuid ;
	}
}


